﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace test
{
    public partial class FormChangePassword : Form
    {
        public User user;
        public FormChangePassword()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
        //修改密码返回按钮
        private void btn_return_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            if (CheckInput())
            {
                if (UpdatePassword() > 0)
                {
                    MessageBox.Show("修改成功！");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("修改失败！");
                }

            }
        }

        //验证输入密码
        public bool CheckInput()
        {
            if (text_password.Text.Trim() == "")
            {
                MessageBox.Show("请输入原密码！");
                return false;
            }
            if (text_password.Text.Trim()!= user.Password)
            {
                MessageBox.Show("原密码输入错误！");
                return false;
            }
            if (text_newpassword.Text.Trim() == "")
            {
                MessageBox.Show("请输入新密码！");
                return false;
            }
            if (text_newpassword2.Text.Trim() == "")
            {
                MessageBox.Show("请再次输入新密码！");
                return false;
            }
            if (text_newpassword.Text.Trim() != text_newpassword.Text.Trim())
            {
                MessageBox.Show("新密码与再次输入新密码不相等！");
                return false;
            }
            return true;
        }//更新密码，大于0更新成功，否则失败
        private int UpdatePassword()
        {
            int result = 0;
            DBHelper dBHelper = new DBHelper();
            //1.创建sql语句
            String sql = String.Format("update user set password='{0}' where id='{1}'", text_newpassword.Text.Trim(), user.Id);
            try
            {
                //创建cmd
                MySqlCommand cmd = new MySqlCommand(sql, dBHelper.Connection);
                //打开连接
                dBHelper.OpenConnection();
                //执行
                result = cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show("修改密码出错：" + e.Message);
            }
            finally
            {
                dBHelper.CloseConnection();
            }
            return result;
        }
    }
}
